/*
 * This file is part of ELCube.
 *
 * ELCube is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ELCube is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with ELCube.  If not, see <https://www.gnu.org/licenses/>.
 */
package cn.nkpro.elcube.components.defaults.cards.header

import cn.nkpro.elcube.annotation.NkNote
import cn.nkpro.elcube.docengine.EnumDocClassify
import cn.nkpro.elcube.docengine.NkAbstractCard
import cn.nkpro.elcube.docengine.model.DocDefIV
import cn.nkpro.elcube.docengine.model.DocHV
import org.apache.commons.lang3.StringUtils
import org.springframework.core.annotation.Order
import org.springframework.stereotype.Component

@Order(11)
@NkNote("伙伴抬头")
@Component("NkCardHeaderPartner")
class NkCardHeaderPartner extends NkAbstractCard<Map,Def> {

    @Override
    boolean supports(String classify) {
        return StringUtils.equals(classify, EnumDocClassify.PARTNER.name())
    }

    @Override
    String getPosition() {
        return POSITION_HEADER
    }

    @Override
    Map afterGetData(DocHV doc, Map data, DocDefIV defIV, Def d) {
        doc.setPartnerName(doc.getDocName())
        return super.afterGetData(doc, data, defIV, d) as Map
    }

    @Override
    Map calculate(DocHV doc, Map data, DocDefIV defIV, Def d, boolean isTrigger, Object options) {
        /*
         * 如果单据交易伙伴名称SpEL 不为空，以用户配置的表达式结果为准
         * 否则，单据引擎会自动查找单据最新的单据名称
         */
        if(StringUtils.isNotBlank(d.getPartnerNameSpEL())){
            def context = spELManager.createContext(doc)
            doc.setDocName(spELManager.invoke(d.getPartnerNameSpEL(), context) as String)
        }
        doc.setPartnerName(doc.getDocName())
        return super.calculate(doc, data, defIV, d, isTrigger, options) as Map
    }

    @Override
    Map beforeUpdate(DocHV doc, Map data, Map original, DocDefIV defIV, Def d) {
        /*
         * 如果单据交易伙伴名称SpEL 不为空，以用户配置的表达式结果为准
         * 否则，单据引擎会自动查找单据最新的单据名称
         */
        if(StringUtils.isNotBlank(d.getPartnerNameSpEL())){
            def context = spELManager.createContext(doc)
            doc.setDocName(spELManager.invoke(d.getPartnerNameSpEL(), context) as String)
        }
        doc.setPartnerName(doc.getDocName())
        return data
    }

    static class Def implements Serializable{
        Boolean docNumberVisible
        String partnerNameSpEL
    }
}
